package com.zjw.project.weixin.api.tuLing;


import com.zjw.project.weixin.api.tuLing.bean.InputText;
import com.zjw.project.weixin.api.tuLing.bean.Perception;
import com.zjw.project.weixin.api.tuLing.bean.TuLingBean;
import com.zjw.project.weixin.api.tuLing.bean.UserInfo;
import com.zjw.project.weixin.util.WeixinUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;


@Component
public class TuLingAPI {

    /**
     * 图灵机器人api
     */
    private static final String TuLing_POST_URL = "http://openapi.tuling123.com/openapi/api/v2";
    private static final String USER_ID = "zjw";


    /**
     *  对请求参数进行封装
     * @param text
     * @return
     */
    public JSONObject request(String text,String apiKey){

        TuLingBean tuLingBean = new TuLingBean();
        tuLingBean.setReqType(0);
        Perception perception = new Perception();
        InputText inputText = new InputText();
        inputText.setText(text);
        perception.setInputText(inputText);
        tuLingBean.setPerception(perception);

        UserInfo userInfo = new UserInfo();
        userInfo.setApiKey(apiKey);
        userInfo.setUserId(USER_ID);
        tuLingBean.setUserInfo(userInfo);

        //转为json格式
        JSONObject jsonObject = JSONObject.fromObject(tuLingBean);
        return jsonObject;
    }

    /**
     * 发送请求获取响应结果
     * @param jsonObject
     * @return
     */
    public String sendReponse(JSONObject jsonObject){

        JSONObject object = WeixinUtil.httpRequest(TuLing_POST_URL, "POST", jsonObject.toString());
        JSONArray jsonArray = (JSONArray) object.get("results");
        JSONObject jsonObject1 = (JSONObject) jsonArray.get(0);
        JSONObject jsonObject2 = (JSONObject) jsonObject1.get("values");

        String result =  jsonObject2.getString("text");
        return result;
    }


    /**
     *
     * @param text
     * @return
     */
    public String sendMessage(String text,String key){
        JSONObject jsonObject = this.request(text,key);
        String result = this.sendReponse(jsonObject);
        return result;
    }

    private static String[] API_KEY={"160bc76215184671a94a33825d9469a5",
            "a38a07f2386f4abeaf8cb7c027d46286",
            "cbb6dc788c1a47cda4f44bf4e7035c3f",
            "dc83ad93f4a443e4860aea319018a792"};

    private static int KEY_INDEX = 0;

    public static boolean TuLing_KEY_FLAG = true;

    public String send(String text){
        if(TuLing_KEY_FLAG = false){
            return "今天太累了，明天再回复";
        }

        String result = this.sendMessage(text, API_KEY[KEY_INDEX]);
        if ("请求次数超限制！".equals(result)){
            KEY_INDEX++;
            if (KEY_INDEX >= API_KEY.length){
                KEY_INDEX = 0;
                TuLing_KEY_FLAG = false;
                return "今天太累了，明天再回复";
            }
            return this.send(text);
        }
        return result;
    }






}